/*
 * Copyright (c) 2003 EISLAB, Lulea University of Technology.
 * All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwBT Bluetooth stack.
 * 
 * Author: Conny Ohult <conny@sm.luth.se>
 *
 */

/*-----------------------------------------------------------------------------------*/
/* uartif.c
 *
 * Implementation of the HCI UART transport layer for Linux
 */
/*-----------------------------------------------------------------------------------*/

#include "lwbtopts.h"
#include "phybusif.h"
#include "netif/lwbt/hci.h"
#include "lwip/debug.h"

#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <stdio.h>

//#define BAUDRATE B57600
#define BAUDRATE B115200
//#define SERIALDEVICE "/dev/ttyS0" /* change this to whatever tty you are using */
#define SERIALDEVICE "/dev/uart.bluetooth" /* change this to whatever tty you are using */
//#define SERIALDEVICE "/dev/cu.bluetooth" /* change this to whatever tty you are using */
#define _POSIX_SOURCE 1 /* POSIX compliant source */

int fd;
/*-----------------------------------------------------------------------------------*/
/* Initializes the physical bus interface
 */
/*-----------------------------------------------------------------------------------*/

// Forward declarations from iSchmave's library
void initialise(void);
int  open_device(int devID);
void uninitialise(int devID);

// Replacment phybusif_init to work w/ iPhone with fd initialization courtesy of iSchmave
void phybusif_init_new_new(void) {

	printf("   initializing hci device...\n   (thanks iSchmave!)\n");
	initialise();
	fd = open_device(0);
	//uninitialise(fd);

	// Try to adjust attributes of fd from iScmave's library
	
	struct termios oldtio;
	/* Make the file descriptor asynchronous (the manual page says only
	O_APPEND and O_NONBLOCK, will work with F_SETFL...) */
	fcntl(fd, F_SETFL, FASYNC);
  
	tcgetattr(fd,&oldtio); /* Save current port settings */

	/* Set new port settings */
	oldtio.c_cc[VMIN] = 0; /* Block until at least this many chars have been received */
	oldtio.c_cc[VTIME] = 1; /* Timeout value */

	tcsetattr(fd,TCSANOW,&oldtio);
	tcflush(fd, TCIOFLUSH);

}

/*-----------------------------------------------------------------------------------*/
void
phybusif_init(void)
{


  printf("   initializing hci device on ipod touch ...\n  \n");

if (1) {
  int fdbtr;
  struct termios ti;

  if ((fdbtr = open("/dev/btreset", O_RDWR | O_NOCTTY)) < 0 ){
      perror("Unable to open btreset device: ");
      exit(0);
  }
  tcflush(fdbtr, TCIOFLUSH);
  tcgetattr(fdbtr, &ti);
  close(fdbtr);

  //system("/usr/sbin/BlueTool -f ipod_boot.script");
  // Send the core of the iPod boot script by hand
  FILE *out;
  out = fopen("/tmp/tst", "w");

  fprintf(out,"device -d /dev/uart.bluetooth\n");
  fprintf(out,"wake on\nreset pulse 100\n");
  fprintf(out,"hci reset\nbcm -b 2400000\nmsleep 200\n");
  fprintf(out,"bcm -w /etc/bluetool/BCM4325D0_100108.hcd\nmsleep 200\n");

  fprintf(out,"device -s 115200\nwake on\nreset pulse 100\n");
  fprintf(out,"hci reset\nbcm -b 2400000\nmsleep 200\n");
  fprintf(out,"bcm -w /etc/bluetool/BCM4325D0_100108.hcd\nmsleep 200\n");

  fprintf(out,"device -s 115200\nmsleep 200\n");
  fprintf(out,"bcm -b 115200\nmsleep 200\n");

  fprintf(out,"bcm -a 01:02:03:04:05:AB\nbcm -N\n");

  fprintf(out,"wake on\n");
  fprintf(out,"quit\n");
  fclose(out);

  //system("/usr/sbin/BlueTool -f ipod_boot.script > /tmp/btoutput.txt 2> /tmp/bterr.txt");
  system("/usr/sbin/BlueTool -f /tmp/tst > /tmp/btoutput.txt 2> /tmp/bterr.txt");
  //system("/usr/sbin/BlueTool -f /tmp/tst");
  //system("rm /tmp/tst");
  sleep(2);

} else {
  printf("not doing anything special....\n");
}

//  printf("    done resetting at /dev/btreset \n");

  struct termios oldtio, newtio;
  
  /* Open the device to be non-blocking (read will return immediatly) */
  //fd = open(SERIALDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
  fd = open(SERIALDEVICE, O_RDWR | O_NOCTTY);
  if (fd <0) {perror(SERIALDEVICE); exit(-1); }
  
  /* Make the file descriptor asynchronous (the manual page says only
     O_APPEND and O_NONBLOCK, will work with F_SETFL...) */
  fcntl(fd, F_SETFL, FASYNC);
  
  tcgetattr(fd,&oldtio); /* Save current port settings */
  /* Set new port settings */
  cfmakeraw(&newtio);
  newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD; 
  newtio.c_cflag = BAUDRATE | CLOCAL | CRTSCTS; 
  //newtio.c_iflag = 0;
  //newtio.c_oflag = 0;
  //newtio.c_lflag = 0;
  newtio.c_cc[VMIN] = 0; /* Block until at least this many chars have been received */
  newtio.c_cc[VTIME] = 1; /* Timeout value */
  
  tcsetattr(fd,TCSANOW,&newtio);

  cfsetospeed(&newtio, B115200);
  cfsetospeed(&newtio, B115200);

  tcsetattr(fd,TCSANOW,&newtio);

  tcflush(fd, TCIOFLUSH);
}
/*-----------------------------------------------------------------------------------*/
err_t
phybusif_reset(struct phybusif_cb *cb) 
{
  /* Init new ctrl block */
  /* Alloc new pbuf. lwIP will handle dealloc */

  //printf("\n\n   PBUF_POOL_BUFSIZE = %d \n\n\n", PBUF_POOL_BUFSIZE);

  if((cb->p = pbuf_alloc(PBUF_RAW, PBUF_POOL_BUFSIZE, PBUF_POOL)) == NULL) {
    //LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_reset: Could not allocate memory for pbuf\n"));
    printf("error occurred...\n"); fflush(stdout);
    return ERR_MEM; /* Could not allocate memory for pbuf */
  }
  cb->q = cb->p; /* Make p the pointer to the head of the pbuf chain and q to the tail */

//printf(" cb->p = %d \n ", (int) cb->p); fflush(stdout);
  
  cb->tot_recvd = 0;
  cb->recvd = 0; 

  cb->state = W4_PACKET_TYPE;
  return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
err_t
phybusif_input(struct phybusif_cb *cb) 
{
  unsigned char c;
  unsigned char n;

  unsigned char first_flag;
  first_flag = 0;

  //printf("i/o read cb->state = %d\n", cb->state); fflush(stdout);
  //printf("at beginning of phybusif_input...\n");

  while((n = read(fd,&c,1))) {
#ifdef DEBUG_LOW
    if (first_flag==0) {
      printf("     read in: "); fflush(stdout);
      first_flag = 1;
    }
    printf(" 0x%02X", c); fflush(stdout);
#endif
    //printf("cb->state = %d \n", cb->state); fflush(stdout);
    switch(cb->state) {
    case W4_PACKET_TYPE:
      switch(c) {
      case HCI_ACL_DATA_PACKET:
	cb->state = W4_ACL_HDR;
	break;
      case HCI_EVENT_PACKET:
	cb->state = W4_EVENT_HDR;
	break;
      default:
        LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_input: Unknown packet type\n"));
	break;
      }
      break;
    case W4_EVENT_HDR:
      //printf("processing W4_EVENT_HDR...\n"); fflush(stdout);
      ((u8_t *)cb->q->payload)[cb->recvd] = c;
      cb->tot_recvd++;
      cb->recvd++;
      if(cb->recvd == HCI_EVENT_HDR_LEN) {
//#ifdef DEBUG_LOW
//        printf("\n");
//#endif
	cb->evhdr = cb->p->payload;
	pbuf_header(cb->p, -HCI_EVENT_HDR_LEN);
	cb->recvd = cb->tot_recvd = 0;
	if(cb->evhdr->len > 0) {
	  cb->state = W4_EVENT_PARAM;
	} else {
	  hci_event_input(cb->p); /* Handle incoming event */
	  pbuf_free(cb->p);
	  phybusif_reset(cb);
#ifdef DEBUG_LOW
          if (first_flag > 0) { printf("\n (done w/ W4_EVENT_HDR)\n"); }
#endif
	  return ERR_OK; /* Since there most likley won't be any more data in the input buffer */
	}
      }
      break;
    case W4_EVENT_PARAM:
      ((u8_t *)cb->q->payload)[cb->recvd] = c;
      cb->tot_recvd++;
      cb->recvd++;
      if(cb->recvd == cb->q->len) { /* Pbuf full. alloc and add new tail to chain */
        cb->recvd = 0;
        if((cb->q = pbuf_alloc(PBUF_RAW, PBUF_POOL_BUFSIZE, PBUF_POOL)) == NULL) {
	  LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_input: Could not allocate memory for event parameter pbuf\n"));
	  return ERR_MEM; /* Could not allocate memory for pbuf */
	}
	pbuf_chain(cb->p, cb->q);
	pbuf_free(cb->q);
      }
      if(cb->tot_recvd == cb->evhdr->len) {
        //printf("\n going to handle event input....\n");
        //printf("payload going into hci_event_input = %d \n", *((u16_t *)cb->p->payload));
#ifdef DEBUG_LOW
	printf("\n");
#endif
	hci_event_input(cb->p); /* Handle incoming event */
        pbuf_free(cb->p);
	phybusif_reset(cb);
#ifdef DEBUG_LOW
        if (first_flag > 0) { printf(" (done w/ W4_EVENT_PARAM)\n"); }
#endif
        return ERR_OK; /* Since there most likley won't be any more data in the input buffer */
      }
      break;
    case W4_ACL_HDR:
      ((u8_t *)cb->q->payload)[cb->recvd] = c;
      cb->tot_recvd++;
      cb->recvd++;
      if(cb->recvd == HCI_ACL_HDR_LEN) {
#ifdef DEBUG_LOW
	printf("\n");
#endif
	cb->aclhdr = cb->p->payload;
	pbuf_header(cb->p, -HCI_ACL_HDR_LEN);
	cb->recvd = cb->tot_recvd = 0;
	if(cb->aclhdr->len > 0) {
	  cb->state = W4_ACL_DATA;
	} else {
	  LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_reset: Forward Empty ACL packet to higher layer\n"));
	  hci_acl_input(cb->p); /* Handle incoming ACL data */
	  phybusif_reset(cb);
#ifdef DEBUG_LOW
          if (first_flag > 0) { printf(" (done w/ W4_ACL_HDR)\n"); }
#endif
	  return ERR_OK; /* Since there most likley won't be any more data in the input buffer */
	}
      }
      break;
    case W4_ACL_DATA:
      ((u8_t *)cb->q->payload)[cb->recvd] = c;
      cb->tot_recvd++;
      cb->recvd++;
//printf("(fd = %d ", fd);
//printf(" &fd = %d) ", (int) &fd);
      if(cb->recvd == cb->q->len) { /* Pbuf full. alloc and add new tail to chain */
        printf("needing to extend chain... \n");
        cb->recvd = 0;
        if((cb->q = pbuf_alloc(PBUF_RAW, PBUF_POOL_BUFSIZE, PBUF_POOL)) == NULL) {
	  LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_input: Could not allocate memory for ACL data pbuf\n"));
	  printf("\n\nphybusif_input: Could not allocate memory for ACL data pbuf\n");
	  return ERR_MEM; /* Could not allocate memory for pbuf */
	}
        pbuf_chain(cb->p, cb->q);
	pbuf_free(cb->q);
      }
//printf("cb->aclhdr->len = %d \n", cb->aclhdr->len);

      if(cb->tot_recvd == cb->aclhdr->len) {
#ifdef DEBUG_LOW
	printf("\n");
#endif
	LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_input: Forward ACL packet to higher layer\n"));
#ifdef DEBUG_MED
	printf("phybusif_input: Forward ACL packet to higher layer\n");
#endif

//		if (l2cap_insegs != NULL) {
//    printf("   before hci_acl_input: l2cap_insegs->l2caphdr->len = %d \n", l2cap_insegs->l2caphdr->len);
//    printf("   checking: l2cap_insegs->l2caphdr->cid = %d \n", l2cap_insegs->l2caphdr->cid);
//    printf("   after registering: l2cap_insegs->len = %d \n", l2cap_insegs->len);
//    printf("   l2cap_insegs->bd_addr = %02X:%02X:%02X:%02X:%02X:%02X\n", l2cap_insegs->bdaddr.addr[5], l2cap_insegs->bdaddr.addr[4], l2cap_insegs->bdaddr.addr[3], l2cap_insegs->bdaddr.addr[2], l2cap_insegs->bdaddr.addr[1], l2cap_insegs->bdaddr.addr[0]);
//		} else {
//    printf("   l2cap_insegs = NULL \n"); fflush(stdout);
//		}

	hci_acl_input(cb->p); /* Handle incoming ACL data */
        //pbuf_free(cb->p);

//		if (l2cap_insegs != NULL) {
//    printf("   before reset: l2cap_insegs->l2caphdr->len = %d \n", l2cap_insegs->l2caphdr->len);
//    printf("   checking: l2cap_insegs->l2caphdr->cid = %d \n", l2cap_insegs->l2caphdr->cid);
//    printf("   after registering: l2cap_insegs->len = %d \n", l2cap_insegs->len);
//    printf("   l2cap_insegs->bd_addr = %02X:%02X:%02X:%02X:%02X:%02X\n", l2cap_insegs->bdaddr.addr[5], l2cap_insegs->bdaddr.addr[4], l2cap_insegs->bdaddr.addr[3], l2cap_insegs->bdaddr.addr[2], l2cap_insegs->bdaddr.addr[1], l2cap_insegs->bdaddr.addr[0]);
//    printf("               : l2cap_insegs->l2caphdr = %d \n", (int) l2cap_insegs->l2caphdr);
//		}

	phybusif_reset(cb);
#ifdef DEBUG_LOW
        if (first_flag > 0) { printf(" (done w/ W4_ACL_DATA)\n"); }
#endif

//		if (l2cap_insegs != NULL) {
//    printf("   after reset: l2cap_insegs->l2caphdr->len = %d \n", l2cap_insegs->l2caphdr->len);
//    printf("   checking: l2cap_insegs->l2caphdr->cid = %d \n", l2cap_insegs->l2caphdr->cid);
//    printf("   after registering: l2cap_insegs->len = %d \n", l2cap_insegs->len);
//    printf("   l2cap_insegs->bd_addr = %02X:%02X:%02X:%02X:%02X:%02X\n", l2cap_insegs->bdaddr.addr[5], l2cap_insegs->bdaddr.addr[4], l2cap_insegs->bdaddr.addr[3], l2cap_insegs->bdaddr.addr[2], l2cap_insegs->bdaddr.addr[1], l2cap_insegs->bdaddr.addr[0]);
//		} else {
//    printf("   l2cap_insegs = NULL \n"); fflush(stdout);
//		}

//        printf("i/o read cb->state = %d (at end of phybusif_input (after phybusif_rset)) \n", cb->state); fflush(stdout);
        return ERR_OK; /* Since there most likley won't be any more data in the input buffer */
      }
      break;
    default:
      LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_input: Unknown state\n\n"));
      break;
    }
  }

//  printf("at end of phybusif_input...\n");
#ifdef DEBUG_LOW
  if (first_flag > 0) { printf("hey there \n"); }
#endif
  return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
void
phybusif_output(struct pbuf *p, u16_t len) 
{
  static struct pbuf *q;
  static int i;
  static unsigned char *ptr;
  unsigned char c;
 
  /* Send pbuf on UART */
  LWIP_DEBUGF(PHYBUSIF_DEBUG, ("phybusif_output: Send pbuf on UART\n"));
  for(q = p; q != NULL; q = q->next) {
    ptr = q->payload;
#ifdef DEBUG_LOW
    printf("     writing: "); fflush(stdout);
#endif
    for(i = 0; i < q->len && len; i++) {
      c = *ptr++;
#ifdef DEBUG_LOW
      printf(" 0x%02X", c); fflush(stdout);
#endif
      write(fd, &c, 1);
      --len;
    }
#ifdef DEBUG_LOW
    printf("\n"); fflush(stdout);
#endif
  }
}
/*-----------------------------------------------------------------------------------*/
